<?php
/**
 * (logic)（临时转正式）Advertised广告费
 */
namespace App\Logic\MonthlyReport\ParseTmp;

use App\Models\Basics\SysCountry;
use App\Models\MonthlyReport\Payment\AdsMonthly;
use App\Models\MonthlyReport\Tmp\TmpAds;
class ParseAdsMonthly
{
    public static function exeParse($date){
        //临时AdsMonthly
        $lines = TmpAds::query()->selectRaw('country,seller_sku,sum(spend) as spend')
            ->where('report_date',$date)
            ->whereNotNull('seller_sku')
            ->groupBy(['country','seller_sku'])
            ->get();
        $i = 0;
        $num = 200;
        $country = [];
        while(true){
            if($lines->isEmpty())break;
            $_lines = $lines->splice($i,$num);
            foreach ($_lines as $line){
                if(!array_key_exists($line->country,$country)){
                    $countryId = SysCountry::getIdByCountry($line->country);
                    $country[$line->country] = $countryId ?: 0;
                }
                //正式AdsMonthly
                AdsMonthly::query()->updateOrCreate(['report_date' => $date,
                    'country_id' => $country[$line->country],
                    'seller_sku' => $line->seller_sku],
                    ['spend' => $line->spend]);
            }
        }
    }
}
